<?php

namespace app\models;

use Yii;
use yii\db\Expression;
/**
 * This is the model class for table "message".
 *
 * @property integer $id
 * @property integer $sender
 * @property integer $receiver
 * @property string $title
 * @property string $content
 * @property integer $status
 * @property string $dt
 *
 * @property Member $receiver0
 * @property Member $sender0
 */
class Message extends \yii\db\ActiveRecord
{
  const TITLE_THUMB_LEN = 15;
  /*
  * 0 发送位          0 未发出   1 发出  0001
  * 1 草稿箱存在位    0 不存在   1 存在   0010 >>1
  * 2 发件箱存在位    0 不存在   1 存在   0100 >>2
  * 3 收件箱存在位    0 不存在   1 存在   1000 >>3
  * 4 收件人已读位    0 未读     1 已读  10000 >>4
  */
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'message';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['sender', 'receiver', 'title', 'content', 'status'], 'required'],
            [['sender', 'receiver', 'status'], 'integer'],
            [['content'], 'string'],
            [['dt'], 'safe'],
            [['title'], 'string', 'max' => 128],
            [['receiver'], 'exist', 'skipOnError' => true, 'targetClass' => Member::className(), 'targetAttribute' => ['receiver' => 'id']],
            [['sender'], 'exist', 'skipOnError' => true, 'targetClass' => Member::className(), 'targetAttribute' => ['sender' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
          'id' => 'ID',
          'sender' => '发信人',
          'receiver' => '收信人',
          'title' => '标题',
          'content' => '内容',
          'status' => '状态',
          'dt' => '日期',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getReceiver0()
    {
        return $this->hasOne(Member::className(), ['id' => 'receiver']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSender0()
    {
        return $this->hasOne(Member::className(), ['id' => 'sender']);
    }

    public function addDraft($content){
      $message=new Message;
      $message->sender=Yii::$app->user->getId();
      $message->title=Message::getThumbTitle($content);
      $message->content=$content;
      $message->dt=new Expression('NOW()');
      $message->status=(1<<4);//草稿存在，未发出
      if(!$message->save()){
        return false;
      }
      return true;
    }
    public static function getThumbTitle($content){

        $title=strip_tags($content);
        if(function_exists('mb_substr')){
            if(strlen($title) > Message::TITLE_THUMB_LEN){
                $title= mb_substr($title,0,Message::TITLE_THUMB_LEN).'...';
            }
            return $title;
        }else{
            if(strlen($title) > Message::TITLE_THUMB_LEN){
                $title= substr($title,0,Message::TITLE_THUMB_LEN).'...';
            }
            return $title;
        }
    }
    /*
    * 不更改内容直接发送草稿
    */
    public static function sendMessage($id,$receiver,$is_delete_draft){
      $draft=Message::findOne($id);
      if(is_null($draft)){
        return false;
      }
      $receiverobj=Member::find()->where(['name'=>$receiver])->one();
      if(is_null($receiverobj)){
        return false;
      }
      $draft->receiver=$receiverobj->id;
      $draft->dt=new Expression('NOW()');
      if($is_delete_draft){
        $draft->status=(1<<3)|(1<<2)|/*(1<<1)|*/1;
      }else{
        $draft->status=(1<<3)|(1<<2)|(1<<1)|1;
      }

      if(!$draft->save()){
        return false;
      }
      return true;
    }
    public static function addAndSendMessage($content,$receiver,$is_delete_draft){
      $message=new Message;
      $message->sender=Yii::$app->user->getId();
      $receiverobj=Member::find()->where(['name'=>$receiver])->one();
      if(is_null($receiverobj)){
        return false;
      }
      $message->receiver=$receiverobj->id;
      $message->title=Message::getThumbTitle($content);
      $message->content=$content;
      $message->dt=new Expression('NOW()');
      if($is_delete_draft){
        $message->status=(1<<3)|(1<<2)|/*(1<<1)|*/1;
      }else{
        $message->status=(1<<3)|(1<<2)|(1<<1)|1;
      }
      if(!$message->save()){
        return false;
      }
      return true;
    }
    /*
    * 获得消息内容，并可能设置消息为已读
    */
    public static function getMessageContent($msgid,$is_set_readed){
      $message=Message::findOne($msgid);
      if(!is_null($message)){
        if($is_set_readed){
          $message->status=$message->status|16;
          if(!$message->save()){
            //
          }
        }
        return $message->content;
      }
    }
    public static function getMessageSender($msgid){
      $message=Message::find()->where(['id'=>$msgid])->with('sender0')->one();

      if(!is_null($message)){
        return $message->sender0->name;
      }
    }
    public static function delMsg($keys,$activebox){
      $tr = Yii::$app->db->beginTransaction();
      try {
        $models = Message::find()->where(['id'=>$keys])->all();
        foreach($models as $model) {
          switch($activebox){
            case 0://回收站
            $model->status = 0;
            break;
            case 1://草稿（00010）(11101)
            $model->status = ($model->status&29);
            break;
            case 2://发件箱(00100)(11011)
            $model->status = ($model->status&27);
            break;
            case 3://收件箱(01000)(10111)
            $model->status = ($model->status&23);
            break;
            default:
            $model->status = $model->status;
            break;
          }
          if(!$model->update(false)){
            throw new Exception("批量删除失败".print_r(true,$model->errors));
          }
        }
        $tr->commit();
        return true;
      } catch (Exception $e) {
        $tr->rollBack();
        //写日志
        return false;
      }
    }
}
